"use client"
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import {useActionState} from "react";
import {login} from "@/lib/action/login";
import Link from "next/link";
import {ActionState, LoginForm} from "@/lib/zod/types";
import {redirect} from "next/navigation";


const Page = () => {
    const [state, loginFormAction, isPending] = useActionState<ActionState<LoginForm>, FormData>(login, {
        code: 0,
        msg: "",
    });

    if (state.code === 200) {
        return redirect("/home")
    }

    return <>
        <form action={loginFormAction}>
            <div className="flex h-dvh justify-center items-center ">
                <div className="flex flex-col w-96 h-fit gap-3 border border-input bg-slate-50 p-8 rounded mx-2">
                        <div className={"flex items-center"}>
                            <div className={"flex-shrink-0 w-16"}>邮箱：</div>
                            <div className={"flex-grow"}>
                                <Input name={"email"} defaultValue={state.input?.email}/>
                                {
                                    state.errors?.email &&
                                    <p className={"text-red-500 text-sm"}>{state.errors?.email.join("、")}</p>
                                }
                            </div>
                        </div>
                        <div className={"flex items-center"}>
                            <div className={"flex-shrink-0 w-16"}>密码：</div>
                            <div className={"flex-grow"}>
                                <Input name={"password"} type={"password"} defaultValue={state.input?.password} autoComplete={"off"}/>
                                {
                                    state.errors?.password &&
                                    <p className={"text-red-500 text-sm"}>{state.errors?.password.join("、")}</p>
                                }
                            </div>
                        </div>
                        {   state.code === 403
                            &&
                            <p className={"text-red-500 text-sm text-end"}>{state.msg}</p>
                        }

                    <div className={"flex justify-center"}>
                        <Button type={"submit"}>{isPending?"登录中":"登录"}</Button>
                        <Link href={"/register"}><Button variant={"link"} type={"button"}>用户注册</Button></Link>
                    </div>
                </div>
            </div>
        </form>
    </>
}

export default Page;